#include "server.h"

#include <QMessageBox>
#include <QSqlTableModel>
#include <QSqlDatabase>
#include <QSqlError>
#include <QDebug>
#include <QSqlQuery>

Server::Server(QObject *parent, quint16 port) : QTcpServer(parent)
{
    listen(QHostAddress::AnyIPv4, port);
    //connect(this, SIGNAL(newConnection()), SLOT(slotAccept()));
}

Server::~Server()
{

}
/*
void Server::slotAccept()
{
    qDebug() << "newConnection";
}
*/
void Server::incomingConnection(qintptr socket)
{
    /*
        todo mysql: if account and password exist, insert into clients;
                    else sendData to client, refuse connect
    */
    qDebug() << "incomingConnection waiting new connection";
    client = new TcpSocket();
    client->setSocketDescriptor(socket);

    qDebug() << "in server.cpp waiting for read...";
    //qDebug() << client->bytesAvailable();

    connect(client, SIGNAL(disconnected(int)),
            this, SLOT(slotDisconnected(int)));
    connect(client, SIGNAL(updateMsg(QByteArray)),
            this, SLOT(slotUpdate(QByteArray)));

    clients << client;
}

void Server::slotDisconnected(int socketDescrip)
{
    qDebug() << "disconnect client : " << socketDescrip;
    foreach (TcpSocket *c, clients) {
        if(c->socketDescriptor() == socketDescrip)
            clients.removeOne(c);
        return;
    }
}

void Server::slotUpdate(QByteArray datagram)
{
    foreach (TcpSocket *c, clients) {
        c->write(datagram);//turn the data to other client
    }
    emit updateMsg(datagram);
}
